package com.yunduo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunduo.common.RetunData.statuscode.impl.FileCode;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.PFile;
import com.yunduo.entity.vo.FileObj;
import com.yunduo.handler.exceptionhandler.OperationException;
import com.yunduo.mapper.PFileMapper;
import com.yunduo.module.FileStore.FileStore;
import com.yunduo.service.PFileService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * 系统日志服务
 */
@Service("pFileService")
public class PFileServiceImpl extends ServiceImpl<PFileMapper, PFile> implements PFileService {
    @Resource
    private FileStore fileStore;

    //上传文件
    @Override
    public PFile uploadFile(FileObj fileObj) {
        //如果此文件已经存在就不创建
        LambdaQueryWrapper<PFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PFile::getName,fileObj.getName());
        PFile isExist = this.getOne(queryWrapper);
        if(isExist!=null){
            throw new OperationException(FileCode.FILE_IS_EXIST);
        }
        String url = fileStore.upLoadFile(fileObj);
        PFile pFile = new PFile();
        pFile.setName(fileObj.getName());
        pFile.setSize(fileObj.getData().length);
        pFile.setType(fileObj.getType().getEName());
        pFile.setUrl(url);
        this.save(pFile);
        return pFile;
    }

    //下载文件
    @Override
    public InputStream downloadFile(FileObj fileObj) {
        return fileStore.downloadFile(fileObj);
    }

    //删除文件
    @Override
    public boolean removeFile(FileObj fileObj) {
        fileStore.deleteFile(fileObj);
        this.removeById(fileObj.getId());
        return true;
    }

    //根据Url获取文件信息
    public PFile getFileByUrl(String url){
        LambdaQueryWrapper<PFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PFile::getUrl,url);
        return this.getOne(wrapper);
    }

    //根据Url删除文件
    public boolean removeByUrl(String url){
        PFile file = this.getFileByUrl(url);
        FileObj fileObj = YunDuoUtils.getFileObjForPFile(file);
        return this.removeFile(fileObj);
    }
}
